﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HHL_Acc.HHL_BussAcc.DataObject;
using HHL_Acc.HHL_Util;
using HHL_Util;
using HHL_Acc.HHL_EntityAcc;

namespace HHL_Acc
{
    public partial class PhieuXuatKho : Form
    {
        private int count;
        private string strReceiver;
        private string strDeliver;
        private string strExpMethod;
        List<SysExpMethod> exp = new List<SysExpMethod>();
        private int statusForm = 1; // default
        private const String _Idx = "Idx";
        private const String _ExpID = "ExpID";
        private const String _Login = "Login";
        private const String _Receiver = "ReceiverName";
        private const String _ExpMethod = "ExpMethodNameUnicode";
        private const String _Exp_Date = "Exp_Date";
        private const String _Exp_Hour = "Exp_Hour";
        private const String _shiftID = "shiftID";
        private const String _Issue_Year = "Issue_Year";
        private const String _Exp_Number = "Exp_Number";
        private const String _Status = "Status";
        private const String _LastModified = "LastModified";
        private const String _Qty = "Qty";
        private const String _ExpMethodName = "ExpMethodName";
        private const String _ExpName = "ExpName";
        private const String _Exp_Notes = "Exp_Notes";
        private CommonPaging paging = new CommonPaging(2);
       
        private const String _serialFrom = "serialFrom";
        private const String _serialTo = "serialTo";
        private const String _ticketCode = "ticketCode";
        private const String _ticketPrice = "ticketPrice";
        public PhieuXuatKho()
        {
            InitializeComponent();
            initSmiExports();
            
        }
        // khởi tạo datagridview
        private void initGridView()
        {
            try
            {
                // khởi tạo GridView danh sách export
                List<ColumnItem> columnItemsList = new List<ColumnItem>();
                columnItemsList.Add(new ColumnItem(_Idx, "STT", CommonConstant.SEQ_WIDTH));
                columnItemsList.Add(new ColumnItem(_Exp_Number, "Số phiếu", CommonConstant.SEQ_WIDTH));
                columnItemsList.Add(new ColumnItem(_Issue_Year, "Năm", CommonConstant.YEAR_WIDTH));
                columnItemsList.Add(new ColumnItem(_Exp_Date, "Ngày nhập", CommonConstant.DATE_WIDTH));
                columnItemsList.Add(new ColumnItem(_ExpMethod, "Loại xuất", CommonConstant.IMPORT_METHOD_WIDTH));
                columnItemsList.Add(new ColumnItem(_Qty, "Số lượng", CommonConstant.AMOUNT_TICKET_WIDTH));
                columnItemsList.Add(new ColumnItem("Login", "Người giao", CommonConstant.PRICE_WIDTH));
                columnItemsList.Add(new ColumnItem(_Receiver, "Người nhận", CommonConstant.RECEIVER_WIDTH));
                columnItemsList.Add(new ColumnItem(_Exp_Notes, "Ghi chú", CommonConstant.NOTES_WIDTH));
                columnItemsList.Add(new ColumnItem("StationIDNameUnicode", "Trạm", CommonConstant.STATION_WIDTH));
                columnItemsList.Add(new ColumnItem(_Status, "Trạng thái", CommonConstant.STATION_WIDTH));
                CommonGuiUtil.CreateColumns(ref gvExp_ExpList, columnItemsList);
                // khởi tạo GridView phiếu xuất details
                List<ColumnItem> columnItemsList_Details = new List<ColumnItem>();
                columnItemsList_Details.Add(new ColumnItem(_Idx, "STT", CommonConstant.SEQ_WIDTH));
                columnItemsList_Details.Add(new ColumnItem(_ticketPrice, "Mệnh giá", CommonConstant.PRICE_WIDTH));
                columnItemsList_Details.Add(new ColumnItem(_Qty, "Số lượng", CommonConstant.AMOUNT_TICKET_WIDTH));
                columnItemsList_Details.Add(new ColumnItem(_serialFrom, "Serial BĐ", CommonConstant.SERIAL_WIDTH));
                columnItemsList_Details.Add(new ColumnItem(_serialTo, "Serial KT", CommonConstant.SERIAL_WIDTH));
                CommonGuiUtil.CreateColumns(ref gvAdd_Details, columnItemsList_Details);
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }
        private void initSmiExports()
        {
            try
            {
                initGridView();
                txtReceiver_ExpMethod.Text = AppInfo.GenLogin.Name;
                strReceiver = AppInfo.GenLogin.EmpId;
                txtDeliver_ExpMethod.Text = AppInfo.GenLogin.Name;
                strDeliver = AppInfo.GenLogin.EmpId;
                int currYear = DateTime.Now.Year;
                int pos = currYear - 5;
                while (pos < currYear + 5)
                {
                    cbxYear_Details.Items.Add(pos);

                    pos++;
                }
                cbxYear_Details.SelectedIndex = 5;

                // load data 
                var sysExpMethodBus = new SysExpMethodBus();
                
                exp = sysExpMethodBus.GetSysExpMethodList();
                cbxExpMethod_Details.DataSource = exp;
                SmiExportsBus smiExports = new SmiExportsBus();
                int total = smiExports.GetTotalRecord();
                paging.TotalRecords = total;
                paging.PageCount = paging.TotalRecords / paging.PageSize;
                btnBack_ExpList.Enabled = false;
                if ((paging.TotalRecords % paging.PageSize) > 0)
                {
                    paging.PageCount = paging.PageCount + 1;
                }
                int skip;
                skip = paging.CurrentPage * paging.PageSize;

                txtTotal_ExpList.Text =(paging.CurrentPage + 1) + "/" +paging.PageCount;
                gvExp_ExpList.DataSource = smiExports.GetSmiExportDetails(paging.PageSize, skip);
            }
            catch(Exception a){
                MessageBox.Show(a.Message);
            }
        }

        private void btnSearchVote_ExpList_Click(object sender, EventArgs e)
        {

        }

        private void gvExp_ExpList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
           
                int row = e.RowIndex;
                if (row < 0)
                {
                    return;
                }
                else {
                    gvExp_ExpList_CellClick(row);
                }
              
        }
        private void gvExp_ExpList_CellClick(int row)
        {
            try
            {
                if (row < 0)
                {
                    return;
                }
                SmiExports smiExport = new SmiExports();
                txtVote_Details.Text = gvExp_ExpList.Rows[row].Cells[_Exp_Number].Value.ToString();
                cbxYear_Details.Text = gvExp_ExpList.Rows[row].Cells[_Issue_Year].Value.ToString();
                cbxExpMethod_Details.Text = gvExp_ExpList.Rows[row].Cells[_ExpMethod].Value.ToString();
                txtDeliver_ExpMethod.Text = gvExp_ExpList.Rows[row].Cells[_Login].Value.ToString();
                txtReceiver_ExpMethod.Text = gvExp_ExpList.Rows[row].Cells[_Receiver].Value.ToString();
                txtNote_Details.Text = gvExp_ExpList.Rows[row].Cells[_Exp_Notes].Value.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnNext_ExpList_Click(object sender, EventArgs e)
        {
            SmiExportsBus smiExports = new SmiExportsBus();
            int skip;
            if (btnBack_ExpList.Enabled == false)
                btnBack_ExpList.Enabled = true;
            if (paging.CurrentPage < paging.PageCount)
            {
                paging.CurrentPage = paging.CurrentPage + 1;
                skip = paging.CurrentPage * paging.PageSize;
                txtTotal_ExpList.Text = (paging.CurrentPage + 1) + "/" + paging.PageCount;
                gvExp_ExpList.DataSource = smiExports.GetSmiExportDetails(paging.PageSize, skip);
                if (paging.CurrentPage == (paging.PageCount - 1))
                {
                    btnNext_ExpList.Enabled = false;
                    btnEnd_ExpList.Enabled = false;
                }
            }
        }

        private void btnBack_ExpList_Click(object sender, EventArgs e)
        {
            SmiExportsBus smiExports = new SmiExportsBus();
            if (btnNext_ExpList.Enabled == false)
            {
                btnNext_ExpList.Enabled = true;
                btnEnd_ExpList.Enabled = true;
            }
            int skip;
            if (paging.CurrentPage > 0)
            {
                paging.CurrentPage = paging.CurrentPage - 1;
                skip = paging.CurrentPage * paging.PageSize;
                txtTotal_ExpList.Text = (paging.CurrentPage + 1) + "/" + paging.PageCount;
                gvExp_ExpList.DataSource = smiExports.GetSmiExportDetails(paging.PageSize, skip);
                if (paging.CurrentPage == 0)
                {
                    btnBack_ExpList.Enabled = false;
                }
            }
        }

        private void btnEnd_ExpList_Click(object sender, EventArgs e)
        {
            SmiExportsBus smiExports = new SmiExportsBus();
            if (btnNext_ExpList.Enabled == false)
                btnNext_ExpList.Enabled = true;
            int skip;
            paging.CurrentPage = paging.PageCount-1;
            skip = paging.CurrentPage * paging.PageSize;
            txtTotal_ExpList.Text = (paging.CurrentPage + 1) + "/" + paging.PageCount;
            gvExp_ExpList.DataSource = smiExports.GetSmiExportDetails(paging.PageSize, skip);
            btnNext_ExpList.Enabled = false;
            btnEnd_ExpList.Enabled = false;
            btnBack_ExpList.Enabled = true;
            btnFirt_ExpList.Enabled = true;
        }

        private void btnFirt_ExpList_Click(object sender, EventArgs e)
        {
            SmiExportsBus smiExports = new SmiExportsBus();
            int skip;
            paging.CurrentPage = 0;
            skip = paging.CurrentPage * paging.PageSize;
            txtTotal_ExpList.Text = (paging.CurrentPage + 1) + "/" + paging.PageCount;
            gvExp_ExpList.DataSource = smiExports.GetSmiExportDetails(paging.PageSize, skip);
            btnNext_ExpList.Enabled = true;
            btnEnd_ExpList.Enabled = true;
            btnBack_ExpList.Enabled = false;
            btnFirt_ExpList.Enabled = false;
        }

        private void btnAddList_Details_Click(object sender, EventArgs e)
        {
            int from, end;
            string ticketcode;
            string symbol;
            from= int.Parse(txtFromSerial_Details.Text.Substring(9,6));
            end=int.Parse(txtEndSerial_Details.Text.Substring(9,6));
            symbol = txtEndSerial_Details.Text.Substring(0, 7);
            ticketcode = CommonBusUtil.GetSerialTicketCode(txtEndSerial_Details.Text);
            SmiTicketCompBus  smiTicketCompBus=new SmiTicketCompBus();
            if (smiTicketCompBus.isExistTicketComp(from, end, ticketcode, symbol) == false)
            {
                MessageBox.Show("Vé không tồn tại trong kho vé của công ty");
                return;
            }
            if (String.IsNullOrEmpty(txtFromSerial_Details.Text))
            {
                MessageBox.Show("Vui lòng nhập số serail bắt đầu");
                return;
            }
            if (int.Parse(dmVoteAdd_Detail.Text) == 0)
            {
                MessageBox.Show("Vui lòng nhập số số lượng vé nhập ");
                return;
            }
            // kiểm tra vé có tồn tại trong kho vé của công ty hay không
        
            // check exist
            int rowsCount = gvAdd_Details.Rows.Count;
            if (rowsCount > 0)
            {
                String serailFrom = string.Empty;
                for (int i = 0; i < rowsCount; i++)
                {
                    serailFrom = (String)gvAdd_Details.Rows[i].Cells[_serialFrom].Value;
                    if (serailFrom != null)
                    {
                        if (serailFrom.EndsWith(txtFromSerial_Details.Text.ToUpper()))
                        {
                            // exist in gridview
                            return;
                        }
                    }
                }
            }

            if (rowsCount > 0)
            {
                count++;
            }
            //  String donGia = CommonUtil.ConvertCurrencyToString((long)txtTabTTCTDonGiaVe.Value);
            //   String donGia = common
            gvAdd_Details.Rows.Add(new Object[]
                                                  {
                                                      count,
                                                      CommonUtil.ConvertCurrencyToString(long.Parse(HHL_Acc.HHL_Util.AppInfo.AppTicketPrice[CommonBusUtil.GetSerialTicketID(txtFromSerial_Details.Text),CommonBusUtil.GetSerialVehicleID(txtFromSerial_Details.Text)])),
                                                      int.Parse(txtEndSerial_Details.Text.Substring(9, 6)) - int.Parse(txtFromSerial_Details.Text.Substring(9, 6)), // case to int
                                                      txtFromSerial_Details.Text,
                                                      txtEndSerial_Details.Text
                                                  });
        }

        private void txtFromSerial_Details_TextChanged(object sender, EventArgs e)
        {
            if (CommonBusUtil.IsSerial(txtFromSerial_Details.Text) == true)
            {
                txtEndSerial_Details.Text = CommonBusUtil.endSerial(txtFromSerial_Details.Text);
                dmVoteAdd_Detail.Text = "1";
            }
        }

        private void txtEndSerial_Details_TextChanged(object sender, EventArgs e)
        {
            if (CommonBusUtil.IsSerial(txtEndSerial_Details.Text) == true)
            {
                int kq;
                kq = int.Parse(txtEndSerial_Details.Text.Substring(9, 6)) - int.Parse(txtFromSerial_Details.Text.Substring(9, 6));
                dmVoteAdd_Detail.Text = (kq / 100).ToString();
            }
        }

        private void btnSold_Details_Click(object sender, EventArgs e)
        {
            if (btnSold_Details.Text == "Thêm mới")
            {
                // hiển thị thông tin
                disable();
            }
            else {
                InsertForm();
                enable();
            }
        }
        private void enable() {
            btnSold_Details.Text = "Thêm mới";
            btnEdit_Details.Text = "Chỉnh sữa";
            btnDelete_Details.Visible = true;
            btnConfirm_Details.Visible = true;
            btnPrint_Details.Visible = true;
        }
        private void disable() {
            btnSold_Details.Text = "Lưu";
            btnEdit_Details.Text = "Bỏ qua";
            btnDelete_Details.Visible = false;
            btnConfirm_Details.Visible = false;
            btnPrint_Details.Visible = false;
        }
        // insert thông tin phieu xuat
        private void InsertForm()
        {
            // SmiExport Information
            SmiExports smiExports = new SmiExports();
            smiExports.ExpID = CommonUtil.MakeStringID();
            smiExports.Exp_Number = int.Parse(txtVote_Details.Text);
            smiExports.Receiver = strReceiver;
            smiExports.Login = AppInfo.GenLogin.Login;
            smiExports.Exp_Notes = txtNote_Details.Text;

            SysExpMethod sysExpMethod = (SysExpMethod)cbxExpMethod_Details.SelectedItem;
            smiExports.ExpMethod = strExpMethod;
            smiExports.Exp_Date = DateTime.Now.Date;
            smiExports.LastModified = DateTime.Now;
            smiExports.Exp_Hour = CommonUtil.MakeHour();
            smiExports.Issue_Year = DateTime.Now.Year;
            smiExports.Login = AppInfo.GenLogin.Login;
            smiExports.ShiftID = 0;
            smiExports.Status = 0;
            smiExports.StationID = 1;
            // SmiExport information
            List<SmiExportDetails> smiExportDetailList = new List<SmiExportDetails>();
            int rowsCount = gvAdd_Details.Rows.Count;
            SmiExportDetails smiExportDetail = null;
            for (int i = 0; i < rowsCount; i++)
            {
                smiExportDetail = new SmiExportDetails();
                smiExportDetail.ExpID = smiExports.ExpID;
                if (gvAdd_Details.Rows[i].Cells[_serialFrom].Value == null)
                {
                    break;
                }
                smiExportDetail.SerialFrom = (String)gvAdd_Details.Rows[i].Cells[_serialFrom].Value;
                smiExportDetail.TicketPrice = (int)CommonUtil.ConvertStringToCurrency(gvAdd_Details.Rows[i].Cells[_ticketPrice].Value.ToString());
                smiExportDetail.TicketCode = CommonBusUtil.GetSerialTicketCode(smiExportDetail.SerialFrom).ToString();
                smiExportDetail.Status = 0;
                if (gvAdd_Details.Rows[i].Cells[_Qty] != null)
                {
                    smiExportDetail.Qty = (int)gvAdd_Details.Rows[i].Cells[_Qty].Value;

                }
                smiExportDetailList.Add(smiExportDetail);
            }

            SmiExportsBus smiExportsBus = new SmiExportsBus();
            int rslt = smiExportsBus.InsertSmiExport(smiExports, smiExportDetailList);
            if (rslt == 1)
            {
                MessageBox.Show("Thêm mới vé thành công");
            }
            else
            {
                MessageBox.Show("Đã có lỗi xảy ra. Vui lòng kiểm tra lại hệ thống");
            }
        }
        // cập nhật thông tin phiếu xuất
        private void UpdateForm()
        {
            // SmiExport Information
            SmiExports smiExports = new SmiExports();
            smiExports.ExpID = CommonUtil.MakeStringID();
            smiExports.Exp_Number = int.Parse(txtVote_Details.Text);
            smiExports.Receiver = strReceiver;
            smiExports.Login = AppInfo.GenLogin.Login;
            smiExports.Exp_Notes = txtNote_Details.Text;

            SysExpMethod sysExpMethod = (SysExpMethod)cbxExpMethod_Details.SelectedItem;
            smiExports.ExpMethod = strExpMethod;
            smiExports.Exp_Date = DateTime.Now.Date;
            smiExports.LastModified = DateTime.Now;
            smiExports.Exp_Hour = CommonUtil.MakeHour();
            smiExports.Issue_Year = DateTime.Now.Year;
            smiExports.Login = AppInfo.GenLogin.Login;
            smiExports.ShiftID = 0;
            smiExports.Status = 0;
            smiExports.StationID = 1;
            // SmiExport information
            List<SmiExportDetails> smiExportDetailList = new List<SmiExportDetails>();
            int rowsCount = gvAdd_Details.Rows.Count;
            SmiExportDetails smiExportDetail = null;
            for (int i = 0; i < rowsCount; i++)
            {
                smiExportDetail = new SmiExportDetails();
                smiExportDetail.ExpID = smiExports.ExpID;
                if (gvAdd_Details.Rows[i].Cells[_serialFrom].Value == null)
                {
                    break;
                }
                smiExportDetail.SerialFrom = (String)gvAdd_Details.Rows[i].Cells[_serialFrom].Value;
                smiExportDetail.TicketPrice = (int)CommonUtil.ConvertStringToCurrency(gvAdd_Details.Rows[i].Cells[_ticketPrice].Value.ToString());
                smiExportDetail.TicketCode = CommonBusUtil.GetSerialTicketCode(smiExportDetail.SerialFrom).ToString();
                smiExportDetail.Status = 0;
                if (gvAdd_Details.Rows[i].Cells[_Qty] != null)
                {
                    smiExportDetail.Qty = (int)gvAdd_Details.Rows[i].Cells[_Qty].Value;

                }
                smiExportDetailList.Add(smiExportDetail);
            }

            SmiExportsBus smiExportsBus = new SmiExportsBus();
            int rslt = smiExportsBus.InsertSmiExport(smiExports, smiExportDetailList);
            if (rslt == 1)
            {
                MessageBox.Show("Thêm mới vé thành công");
            }
            else
            {
                MessageBox.Show("Đã có lỗi xảy ra. Vui lòng kiểm tra lại hệ thống");
            }
        }
        //private void UpdateForm()
        //{
        //    // throw new NotImplementedException();
        //    // SmiImport Information
        //    if (gvImportListTicket.SelectedRows.Count > 0 && gvImportListTicket.SelectedRows[0] != null)
        //    {
        //        SmiImports smiImports = (SmiImports)gvImportListTicket.SelectedRows[0].DataBoundItem;
        //        //smiImports.ImpId = CommonUtil.MakeStringID();
        //        smiImports.ImpNumber = int.Parse(txtTicketNoDetaitInfo.Text);
        //        smiImports.Deliver = txtDeliverDetailInfo.Text;
        //        smiImports.Importer = AppInfo.GenLogin.Login;
        //        smiImports.NotesVni = txtNoteDetailInfo.Text;

        //        SysImpMethod sysImpMethod = (SysImpMethod)cbImportTypeDetailIinfo.SelectedItem;
        //        smiImports.ImpMethod = sysImpMethod.ImpMethod;
        //        // smiImports.ImpDate = DateTime.Now;
        //        smiImports.LastModified = DateTime.Now;
        //        // smiImports.ImpHour = DateTime.Now.Hour;
        //        smiImports.IssueYear = DateTime.Now.Year;
        //        smiImports.Login = AppInfo.GenLogin.Login;
        //        smiImports.ShiftId = 0;
        //        smiImports.Status = 0;

        //        // SmiImport information
        //        List<SmiImportDetails> smiImportDetailList = new List<SmiImportDetails>();
        //        int rowsCount = gvDetailTicketDetailInfo.Rows.Count;
        //        SmiImportDetails smiImportDetail = null;
        //        for (int i = 0; i < rowsCount; i++)
        //        {
        //            smiImportDetail = new SmiImportDetails();
        //            smiImportDetail.ImpID = smiImports.ImpId;
        //            if (gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value == null)
        //            {
        //                break;
        //            }
        //            smiImportDetail.SerialFrom = (String)gvDetailTicketDetailInfo.Rows[i].Cells["SerialStart"].Value;
        //            //smiImportDetail.Price = int.Parse((String) gvDetailTicketDetailInfo.Rows[i].Cells["Price"].Value);
        //            smiImportDetail.TicketCode =
        //                CommonBusUtil.GetSerialTicketCode(smiImportDetail.SerialFrom).ToString();
        //            smiImportDetail.Status = 0;
        //            if (gvDetailTicketDetailInfo.Rows[i].Cells["Amount"] != null)
        //            {
        //                smiImportDetail.Quality = (int)gvDetailTicketDetailInfo.Rows[i].Cells["Amount"].Value;
        //            }
        //            smiImportDetailList.Add(smiImportDetail);
        //        }
        //        SmiImportsBus smiImportsBus = new SmiImportsBus();
        //        int rslt = smiImportsBus.UpdateSmiImport(smiImports, smiImportDetailList);
        //        if (rslt == 1)
        //        {
        //            MessageBox.Show("Cập nhật vé thành công");
        //        }
        //        else
        //        {
        //            MessageBox.Show("Đã có lỗi xảy ra. Vui lòng kiểm tra lại hệ thống");
        //        }
        //    }
        //}
        private void btnEdit_Details_Click(object sender, EventArgs e)
        {
            if (btnEdit_Details.Text == "Chỉnh sữa")
            {
                // hiển thị thông tin
                disable();
            }
            else
            {

                enable();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void cbxExpMethod_Details_SelectedIndexChanged(object sender, EventArgs e)
        {
            strExpMethod = exp[cbxExpMethod_Details.SelectedIndex].ExpMethod.ToString();
            //MessageBox.Show(strExpMethod);
        }
    }
}